package com.scs.application.core.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.scs.application.core.utils.StringUtils;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 用于前台查询时接收提交的数据
 *
 */

@Data
@EqualsAndHashCode(callSuper = false)
public class PageRequest {

    protected final int MAX_PAGE_SIZE = 200;

    /**
     * mybatis-plus分页参数
     */
    @JsonIgnore
    @JSONField(serialize = false)
    private transient Page page;
    /**
     * 当前页码
     */
    private int currPage = 1;
    /**
     * 每页条数
     */
    private int pageSize = 10;

    /**
     * 排序字段
     */
    private String sidx;

    /**
     * 排序顺序。取值为：asc（升序） desc（降序）
     */
    private String order;

    /**
     * 是否启用分页，默认为true
     */
    private Boolean enabledPage = Boolean.TRUE;

    /**
     * 删除标记（0：正常；1：删除；）
     */
    public static final String DEL_FLAG_NORMAL = "0";
    public static final String DEL_FLAG_DELETE = "1";

    public PageRequest() {

    }

    public PageRequest(int currPage, int pageSize) {
        this.currPage = currPage;
        this.pageSize = pageSize;
    }

    @JsonIgnore
    public IPage getPage() {

        if(pageSize >= MAX_PAGE_SIZE){
            pageSize = MAX_PAGE_SIZE;
        }
        //mybatis-plus分页
        if (this.page == null) {
            this.page = new Page(currPage, pageSize);
        }
        //排序
        if (StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)) {

            switch (this.getOrder()) {
                case "asc":
                    this.page.setAscs(Lists.newArrayList(getSidx()));
                    break;
                case "desc":
                    this.page.setDescs(Lists.newArrayList(getSidx()));
                    break;
                default:
                    this.page.setAsc(getSidx());
            }
        }
        return this.page;
    }


    public String getOrder() {
        if (order == null) {
            return "asc";
        }
        switch (this.order.toLowerCase()) {
            case "ascending":
            case "asc":
                return "asc";
            case "descending":
            case "desc":
                return "desc";
            default:
                return "asc";
        }
    }

    public String getSidx(){
        return StringUtils.uncamelCase(sidx);
    }


}

